import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import NProgress from 'nprogress'
import { getToken } from '@/utils/auth'

// 布局组件
const Layout = () => import('@/components/layout/Layout.vue')

// 路由配置
const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/Login.vue'),
    meta: {
      title: '登录',
      requireAuth: false,
      hideInMenu: true
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/auth/Register.vue'),
    meta: {
      title: '注册',
      requireAuth: false,
      hideInMenu: true
    }
  },
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/dashboard',
    component: Layout,
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/Dashboard.vue'),
        meta: {
          title: '仪表板',
          icon: 'DataBoard',
          requireAuth: true
        }
      }
    ]
  },
  {
    path: '/products',
    component: Layout,
    redirect: '/products/list',
    meta: {
      title: '商品管理',
      icon: 'Box',
      requireAuth: true
    },
    children: [
      {
        path: 'list',
        name: 'ProductList',
        component: () => import('@/views/products/ProductList.vue'),
        meta: {
          title: '商品列表',
          icon: 'Menu',
          requireAuth: true
        }
      },
      {
        path: 'create',
        name: 'ProductCreate',
        component: () => import('@/views/products/ProductForm.vue'),
        meta: {
          title: '新增商品',
          icon: 'CirclePlus',
          requireAuth: true,
          hideInMenu: true
        }
      },
      {
        path: 'edit/:id',
        name: 'ProductEdit',
        component: () => import('@/views/products/ProductForm.vue'),
        meta: {
          title: '编辑商品',
          requireAuth: true,
          hideInMenu: true
        }
      },
      {
        path: 'detail/:id',
        name: 'ProductDetail',
        component: () => import('@/views/products/ProductDetail.vue'),
        meta: {
          title: '商品详情',
          requireAuth: true,
          hideInMenu: true
        }
      },
      {
        path: 'categories',
        name: 'ProductCategories',
        component: () => import('@/views/products/CategoryList.vue'),
        meta: {
          title: '商品分类',
          icon: 'Folder',
          requireAuth: true
        }
      }
    ]
  },
  {
    path: '/suppliers',
    component: Layout,
    redirect: '/suppliers/list',
    meta: {
      title: '供应商管理',
      icon: 'OfficeBuilding',
      requireAuth: true
    },
    children: [
      {
        path: 'list',
        name: 'SupplierList',
        component: () => import('@/views/suppliers/SupplierList.vue'),
        meta: {
          title: '供应商列表',
          icon: 'Menu',
          requireAuth: true
        }
      },
      {
        path: 'create',
        name: 'SupplierCreate',
        component: () => import('@/views/suppliers/SupplierForm.vue'),
        meta: {
          title: '新增供应商',
          icon: 'CirclePlus',
          requireAuth: true,
          hideInMenu: true
        }
      },
      {
        path: 'edit/:id',
        name: 'SupplierEdit',
        component: () => import('@/views/suppliers/SupplierForm.vue'),
        meta: {
          title: '编辑供应商',
          requireAuth: true,
          hideInMenu: true
        }
      },
      {
        path: 'detail/:id',
        name: 'SupplierDetail',
        component: () => import('@/views/suppliers/SupplierDetail.vue'),
        meta: {
          title: '供应商详情',
          requireAuth: true,
          hideInMenu: true
        }
      }
    ]
  },
  {
    path: '/traceability',
    component: Layout,
    redirect: '/traceability/records',
    meta: {
      title: '溯源管理',
      icon: 'Search',
      requireAuth: true
    },
    children: [
      {
        path: 'records',
        name: 'TraceabilityRecords',
        component: () => import('@/views/traceability/TraceList.vue'),
        meta: {
          title: '溯源记录',
          icon: 'Menu',
          requireAuth: true
        }
      },
      {
        path: 'search',
        name: 'TraceabilitySearch',
        component: () => import('@/views/traceability/TraceSearch.vue'),
        meta: {
          title: '溯源查询',
          icon: 'Search',
          requireAuth: true
        }
      },
      {
        path: 'detail/:id',
        name: 'TraceabilityDetail',
        component: () => import('@/views/traceability/TraceDetail.vue'),
        meta: {
          title: '溯源详情',
          requireAuth: true,
          hideInMenu: true
        }
      }
    ]
  },
  {
    path: '/quality',
    component: Layout,
    redirect: '/quality/records',
    meta: {
      title: '质量管理',
      icon: 'DocumentChecked',
      requireAuth: true
    },
    children: [
      {
        path: 'records',
        name: 'QualityRecords',
        component: () => import('@/views/quality/QualityList.vue'),
        meta: {
          title: '质量记录',
          icon: 'Menu',
          requireAuth: true
        }
      },
      {
        path: 'inspection',
        name: 'QualityInspection',
        component: () => import('@/views/quality/InspectionForm.vue'),
        meta: {
          title: '质量检测',
          icon: 'DocumentChecked',
          requireAuth: true
        }
      },
      {
        path: 'reports',
        name: 'QualityReports',
        component: () => import('@/views/quality/QualityReports.vue'),
        meta: {
          title: '质量报告',
          icon: 'Files',
          requireAuth: true
        }
      }
    ]
  },
  {
    path: '/statistics',
    component: Layout,
    redirect: '/statistics/sales',
    meta: {
      title: '数据统计',
      icon: 'TrendCharts',
      requireAuth: true
    },
    children: [
      {
        path: 'sales',
        name: 'SalesStatistics',
        component: () => import('@/views/statistics/SalesReport.vue'),
        meta: {
          title: '销售统计',
          icon: 'TrendCharts',
          requireAuth: true
        }
      },
      {
        path: 'quality',
        name: 'QualityStatistics',
        component: () => import('@/views/statistics/QualityReport.vue'),
        meta: {
          title: '质量统计',
          icon: 'DataAnalysis',
          requireAuth: true
        }
      },
      {
        path: 'inventory',
        name: 'InventoryStatistics',
        component: () => import('@/views/statistics/InventoryReport.vue'),
        meta: {
          title: '库存统计',
          icon: 'DataBoard',
          requireAuth: true
        }
      }
    ]
  },
  {
    path: '/system',
    component: Layout,
    redirect: '/system/users',
    meta: {
      title: '系统管理',
      icon: 'Setting',
      requireAuth: true,
      roles: ['admin']
    },
    children: [
      {
        path: 'users',
        name: 'SystemUsers',
        component: () => import('@/views/system/UserList.vue'),
        meta: {
          title: '用户管理',
          icon: 'Avatar',
          requireAuth: true,
          roles: ['admin']
        }
      },
      {
        path: 'roles',
        name: 'SystemRoles',
        component: () => import('@/views/system/RoleList.vue'),
        meta: {
          title: '角色管理',
          icon: 'Avatar',
          requireAuth: true,
          roles: ['admin']
        }
      },
      {
        path: 'logs',
        name: 'SystemLogs',
        component: () => import('@/views/system/LogList.vue'),
        meta: {
          title: '系统日志',
          icon: 'Files',
          requireAuth: true,
          roles: ['admin']
        }
      },
      {
        path: 'permissions',
        name: 'SystemPermissions',
        component: () => import('@/views/system/PermissionList.vue'),
        meta: {
          title: '权限管理',
          icon: 'Lock',
          requireAuth: true,
          roles: ['admin']
        }
      }
    ]
  },
  {
    path: '/profile',
    component: Layout,
    redirect: '/profile/info',
    meta: {
      title: '个人中心',
      hideInMenu: true
    },
    children: [
      {
        path: 'info',
        name: 'ProfileInfo',
        component: () => import('@/views/profile/ProfileInfo.vue'),
        meta: {
          title: '个人信息',
          requireAuth: true
        }
      },
      {
        path: 'settings',
        name: 'ProfileSettings',
        component: () => import('@/views/profile/ProfileSettings.vue'),
        meta: {
          title: '个人设置',
          requireAuth: true
        }
      }
    ]
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/views/error/404.vue'),
    meta: {
      title: '页面不存在',
      hideInMenu: true
    }
  },
  {
    path: '/403',
    name: 'Forbidden',
    component: () => import('@/views/error/403.vue'),
    meta: {
      title: '无权访问',
      hideInMenu: true
    }
  },
  {
    path: '/500',
    name: 'ServerError',
    component: () => import('@/views/error/500.vue'),
    meta: {
      title: '服务器错误',
      hideInMenu: true
    }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
]

// 创建路由实例
const router = createRouter({
  history: window.location.protocol === 'file:' ? createWebHashHistory() : createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 开始进度条
  NProgress.start()
  
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 超市商品溯源管理系统` : '超市商品溯源管理系统'
  
  // 获取token
  const token = getToken()
  
  console.log('路由守卫 - 目标路径:', to.path, 'Token:', !!token)
  
  if (to.meta.requireAuth) {
    // 需要认证的路由
    if (!token) {
      console.log('需要认证但无Token，跳转到登录页')
      next('/login')
      return
    }
    
    // 检查角色权限
    if (to.meta.roles && to.meta.roles.length > 0) {
      const userRole = localStorage.getItem('userRole')
      if (!to.meta.roles.includes(userRole)) {
        console.log('权限不足，跳转到403页面')
        next('/403')
        return
      }
    }
  } else {
    // 不需要认证的路由
    if (token && (to.path === '/login' || to.path === '/register')) {
      console.log('已登录用户访问登录页，跳转到首页')
      next('/dashboard')
      return
    }
  }
  
  console.log('路由守卫通过，继续导航')
  next()
})

router.afterEach(() => {
  // 结束进度条
  NProgress.done()
})

export default router